class Promise {
  constructor(executor) {
    // 添加属性
    this.PromiseState = "pendding";
    this.PromiseResult = null;
    // 成功状态的回调
    this.onFulfilledCallbacks = [];
    // 失败状态的回调
    this.onRejectedCallbacks = [];

    const resolve = (value) => {
      if (this.PromiseState === "pendding") {
        this.PromiseState = "fulfilled";
        this.PromiseResult = value;
        // 发布
        this.onFulfilledCallbacks.forEach((fn) => fn());
      }
    };
    const reject = (reason) => {
      if (this.PromiseState === "pendding") {
        this.PromiseState = "rejected";
        this.PromiseResult = reason;
        // 发布
        this.onRejectedCallbacks.forEach((fn) => fn());
      }
    };

    try {
      executor(resolve, reject);
    } catch (e) {
      reject(e);
    }
  }
  then(onFulfilled, onRejected) {
    let promise2 = new Promise((resolve, reject) => {
      // 封装函数 处理不同的回调
      let callback = (type) => {
        try {
          let result = type(this.PromiseResult);
          //   console.log(result);
          if (result instanceof Promise) {
            // 如果结果是个Promise对象
            result.then(
              (v) => {
                resolve(v);
              },
              (r) => {
                reject(r);
              }
            );
          } else {
            // 返回的结果是个普通值
            resolve(result);
          }
        } catch (error) {
          reject(error);
        }
      };
      if (this.PromiseState === "fulfilled") {
        callback(onFulfilled);
      }
      if (this.PromiseState === "rejected") {
        callback(onRejected);
      }
      if (this.PromiseState === "pendding") {
        // 订阅
        this.onFulfilledCallbacks.push(() => {
          // onFulfilled(this.PromiseResult);
          callback(onFulfilled);
        });
        // 订阅
        this.onRejectedCallbacks.push(() => {
          // onRejected(this.PromiseResult);
          callback(onRejected);
        });
      }
    });
    return promise2;
  }
}

module.exports = Promise;
